import { init } from 'snabbdom/build/package/init';
import { classModule } from 'snabbdom/build/package/modules/class';
import { propsModule } from 'snabbdom/build/package/modules/props';
import { styleModule } from 'snabbdom/build/package/modules/style';
import { eventListenersModule } from 'snabbdom/build/package/modules/eventlisteners';
import { h } from 'snabbdom/build/package/h'; // helper function for creating vnodes
import data from './data.json';

const patch = init([
  // Init patch function with chosen modules
  classModule, // makes it easy to toggle classes
  propsModule, // for setting properties on DOM elements
  styleModule, // handles styling on elements with support for animations
  eventListenersModule, // attaches event listeners
]);

const container = document.getElementById('app');

const thead = h('thead', [
  h('th', '省份'),
  h('th', '城市'),
  h('th', '最低气温'),
  h('th', '最高气温'),
]);
const geneTableBody = (data) =>
  h(
    'tbody',
    data.map((item) =>
      h(
        'tr',
        [
          h('td', item.quName),
          h('td', item.cityname),
          h('td', item.tem1),
          h('td', item.tem2),
        ]
      )
    )
  );
let tbody = geneTableBody(data);
const table = h('table', { props: { border: true } }, [thead, tbody]);
const changeSort = (type) => {
  let newData = data;
  switch (type) {
    case 'min':
      newData = data.sort((a, b) => a.tem1 - b.tem1);
      break;
    case 'max':
      newData = data.sort((a, b) => a.tem2 - b.tem2);
      break;
    default:
      break;
  }
  patch(tbody, geneTableBody(newData));
};
const buttons = h('div', [
  h('button', { on: { click: [(e) => changeSort('min')] } }, '按最低气温排序'),
  h('button', { on: { click: [(e) => changeSort('max')] } }, '按最高气温排序'),
]);
const body = h('div', [buttons, table]);
patch(container, body);
